<?php

declare(strict_types=1);

namespace app\model;

use think\exception\HttpException;
use app\model\admin\SysUser as SysUserModel;
use think\facade\Db;

/**
 * @mixin \think\Model
 */
class AdminBaseModel extends BaseModel
{
    /**
     * 是否开启数据权限范围
     */
    protected $scopeField = false;

    /**
     * 是否有 field
     * todo 是否删除
     *
     * @time 2020年11月23日
     * @param string $field
     * @return bool
     */
    public function hasField(string $field)
    {
        return property_exists($this, 'field') && in_array($field, $this->field);
    }

    /**
     * 插入前置事件
     */
    public static function onBeforeInsert($model)
    {
        unset($model->id);
        if ($model->scopeField == true) {
            $model->create_by = request()->create_by;
        }
        // $model->created_time = time();
        // $model->updated_time = time();

        $model->created_at = time();
        $model->updated_at = time();
    }
    /**
     * 更新前置事件
     */
    public static function onBeforeUpdate($model)
    {

        if ($model->scopeField == true) {
            //权限操作范围判断
            $model->scopePermissionCheck();
            $model->update_by = request()->create_by;
        }
        unset($model->create_time);
        unset($model->create_by);
        unset($model->id);

        unset($model->created_time);
        unset($model->created_at);

        $model->updated_time = time();
        $model->updated_at = time();
    }
    /**
     * 删除前置事件
     */
    public static function onBeforeDelete($model)
    {

        if (in_array($model->id, $model->noDeletionId)) {
            throw new HttpException(200, '此数据禁止删除');
        }
        if ($model->scopeField == true) {
            //权限操作范围判断
            $model->scopePermissionCheck();
        }
    }

    public function scopeDataFilter($query)
    {
        if ($this->scopeField !== true) {
            return $query;
        }
        //获取id和权限范围
        $scope_info = $this->getCreateIds();
        // var_dump($scope_info);
        if ($scope_info['scope'] == 'all') {
            return $query;
        }
        if ($scope_info['scope'] == 'limit') {
            return $query->whereIn('create_by', $scope_info['ids']);
        }

        return $query->where('create_by', request()->create_by);
    }
    // 获取符合数据权限范围的用户id
    public function getCreateIds()
    {

        $user_id = request()->create_by;
        if ($user_id == 100) {
            return ['scope' => 'all'];
        }
        $user = SysUserModel::with(['roles'])->where('id', $user_id)->find();
        //获取用户角色
        $user_roles = $user->roles;

        $dept_ids = [];
        $user_ids = [];

        //过滤权限
        foreach ($user_roles as $role) {
            // 全部数据权限
            if ($role->data_scope == '1') {
                return ['scope' => 'all'];
            }
            //自定数据权限
            if ($role->data_scope == '2') {
                //获取角色部门关联数据
                $role_dept_ids = Db::table('sys_role_dept')->where('role_id', $role->id)->column('dept_id');
                if ($role_dept_ids) {
                    $dept_ids = array_merge($dept_ids, $role_dept_ids);
                }
            }
            //本部门数据权限
            if ($role->data_scope == '3') {
                //获取用户所属部门
                $dept_ids = array_merge($dept_ids, [$user->dept_id]);
            }
            //本部门及以下数据权限
            if ($role->data_scope == '4') {
                //获取用户部门以及相关下属部门
                $user_dept_and_child_dept_ids = Db::table('sys_dept')->where('ancestors', 'like', '%,' . $user->dept_id . '%')->column('id');
                if ($user_dept_and_child_dept_ids) {
                    $dept_ids = array_merge($dept_ids, $user_dept_and_child_dept_ids);
                }
            }

            //本人数据
            if ($role->data_scope == '5') {
                $user_ids = array_merge($user_ids, [$user_id]);
            }

            //本人数据以及我创建的数据
            if ($role->data_scope == '6') {
                $tmp_user_ids = SysUserModel::where('create_by', $user_id)->column('id');
                if ($tmp_user_ids) {
                    $user_ids = array_merge($user_ids, $tmp_user_ids->toArray());
                }
            }
        }
        //部门相关关联数据
        if (count($dept_ids) > 0) {
            $user_in_depts_ids = SysUserModel::whereIn('dept_id', $dept_ids)->column('id');
            if ($user_in_depts_ids) {
                $user_ids = array_merge($user_ids, $user_in_depts_ids->toArray());
            }
        }
        //没有数据集范围 默认只能看自己的
        if (count($user_ids) == 0) {
            $user_ids = [$user_id];
        }
        return ['scope' => 'limit', 'ids' => $user_ids];
    }

    public function scopePermissionCheck()
    {

        $scope_info = $this->getCreateIds();

        $data_creator = $this->getAttr('create_by');
        if ($scope_info['scope'] == 'limit' && !in_array($data_creator, $scope_info['ids'])) {
            //todo 记录非法操作
            throw new HttpException(200, '非法数据操作');
        }
    }
}
